//
//  HLFConfigManager.m
//  Test
//
//  Created by ChenYuan on 2020/9/18.
//  Copyright © 2020 ChenYuan. All rights reserved.
//

#import "HLFConfigManager.h"
#import <CommonCrypto/CommonDigest.h>
#import "UIViewController+HLF.h"
#import "HLNetworkingManager.h"
#import "DDMainViewController.h"
#import "HLFKit.h"

@implementation HLFConfigManager

+ (void)load
{
    [super load];

    // Config
    [[HLFConfigManager sharedInstance] configWithAddress];
}

#pragma mark - LifeCycle

+ (instancetype)sharedInstance
{
    static HLFConfigManager *configManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        configManager = [[HLFConfigManager alloc] init];
    });
    
    return configManager;
}

#pragma mark - SetupData

- (void)configWithAddress
{
    // 请求    
    NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
    NSArray <NSString *>*bundles = [bundleIdentifier componentsSeparatedByString:@"."];
     NSString *appSign = bundleIdentifier;
     if (bundles.count == 3) {
         appSign = bundles[1];
     }
    
    NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
    NSString *version = dict[@"CFBundleShortVersionString"];
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"version"] = version;
    params[@"appSign"] = appSign;
    params[@"platform"] = @"iOS";
    params[@"timeStamp"] = [NSString stringWithFormat:@"%ld", (long)[[NSDate date] timeIntervalSince1970]];
    
    NSMutableDictionary *signDic = [NSMutableDictionary dictionaryWithDictionary:params];
    signDic[@"signParam"] = bundleIdentifier;
    params[@"sign"] = [self sortedDictionary:signDic];

    [[HLNetworkingManager sharedInstance] requestBaseUrl:kBaseUrl
                                             withAddress:kAppCongfigAddress
                                                  params:params
                                              requesType:HLFRequestTypeGet
                                           completeBlock:^(id responseObject , BOOL isSuccess) {
        if (isSuccess && [responseObject isKindOfClass:[NSDictionary class]]) {
            
            NSString *urlStr = responseObject[@"h5Url"];
            if (urlStr.length) {
                DDMainViewController *vc = [[DDMainViewController alloc] init];
                vc.redirectUrl = urlStr;
                UINavigationController *navigationVC = [[UINavigationController alloc] initWithRootViewController:vc];
                navigationVC.modalPresentationStyle = UIModalPresentationFullScreen;
                [[UIViewController hlf_toppestViewController] presentViewController:navigationVC animated:YES completion:nil];
            }
        }
    }];
}

- (NSString *)sortedDictionary:(NSDictionary *)dict
{
    //将所有的key放进数组
    NSArray *allKeyArray = [dict allKeys];
    
    //序列化器对数组进行排序的block 返回值为排序后的数组
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        //排序操作
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest;
    }];
    NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    
    //通过排列的key值获取value
    __block NSString *paramStr = nil;
    [afterSortKeyArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSString *sortsing = (NSString *)obj;
        
        NSString *valueString = [dict objectForKey:sortsing];
        NSString *tempStr = [sortsing stringByAppendingFormat:@"=%@", valueString];
        
        if (idx == 0) {
            paramStr = tempStr;
        } else {
            paramStr = [paramStr stringByAppendingString:@"&"];
            paramStr = [paramStr stringByAppendingString:tempStr];
        }
    }];
    
    // MD5
    paramStr = [self hlf_md5:paramStr];
    NSLog(@"MD5-paramStr:%@",paramStr);

    return paramStr;
}

- (NSString *)hlf_md5:(NSString *)paramStr
{
    if (!self) {
        return nil;
    }
    const char *cStr = [paramStr UTF8String];//转换成utf-8
    unsigned char result[CC_MD5_DIGEST_LENGTH];//开辟一个16字节（128位：md5加密出来就是128位/bit）的空间（一个字节=8字位=8个二进制数）
    CC_MD5( cStr, (CC_LONG)(strlen(cStr)), result );
    /*
     extern unsigned char *CC_MD5(const void *data, CC_LONG len, unsigned char *md)官方封装好的加密方法
     把cStr字符串转换成了32位的16进制数列（这个过程不可逆转） 存储到了result这个空间中
     */
    NSString* s = [NSString stringWithFormat:
                   @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
                   result[0], result[1], result[2], result[3],
                   result[4], result[5], result[6], result[7],
                   result[8], result[9], result[10], result[11],
                   result[12], result[13], result[14], result[15]
                   ];
    /*
     x表示十六进制，%02X  意思是不足两位将用0补齐，如果多余两位则不影响
     NSLog("%02X", 0x888);  //888
     NSLog("%02X", 0x4); //04
     */
    return s;
}


@end
